<template>
    <div id="add-user">
        <Title title="机构信息"/>
        <el-button size="small" @click="exit" type="primary">返回</el-button>
        <el-button style="float: right;margin-right: 5%" @click="handleEdit"  size="small"  type="primary">添加角色</el-button>
        <div id="form">
            <span class="grname">机构名:</span> <span class="grname1">{{$route.query.group.groupName}}</span>
            <span class="type">机构类型:</span> <span class="grname1">{{$route.query.group.groupType}}</span>
            <span class="gradd">机构地址:</span>  <span class="grname1">{{$route.query.group.address}}</span>

        </div>

        <Title title="机构所属角色"/>

        <el-table border
                :data="tableData.filter(item=>{
                            if (item.role===1){
                                item.role = '一级管理员';
                                }else if (item.role===3){
                                item.role = '二级管理员';
                                }else if (item.role===4){
                                item.role = '三级管理员';
                                }
                                return item;
                                })">
            <el-table-column label="手机号" prop="phone"/>
            <el-table-column label="电子邮箱" prop="email"/>
            <el-table-column label="角色" prop="role"/>
            <el-table-column label="操作"
                    align="center">
                <template slot-scope="scope">

                    <el-button
                            size="mini"
                            type="danger"
                            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--        分页-->
        <Pagination path="/api/Studies_to_travel/user/queryGroupByPages"
                    :count="count"
                    :item="item"
                    @transfer="transfer"
        />
        <!--        修改弹出=框-->

        <el-dialog title="修改机构信息" :visible.sync="dialogFormVisible">

<!--            表单-->
            <el-form  ref="ruleForm1" status-icon label-width="80px" style="margin-left: 20%" :model="form" :rules="rules" >
                <el-form-item prop="phone"  label="手机号" >
                    <el-input v-model="form.phone" max="11" style="width: 300px"  placeholder="请输入内容"/>
                </el-form-item>

<!--                邮箱-->
                <el-form-item prop="email"  label="邮箱" >
                    <el-input v-model="form.email" style="width: 300px"  placeholder="请输入内容"/>
                </el-form-item>

<!--                密码-->
                <el-form-item label="密码"  prop="pwd">
                    <el-input type="password" max="16" style="width: 300px" v-model="form.pwd" placeholder="6-16位密码，区分大小写"/>
                </el-form-item>
                <el-form-item label="确认密码" prop="checkPass">
                    <el-input type="password" max="16"  style="width: 300px"  v-model="form.checkPass" placeholder="确认密码"/>
                </el-form-item>

<!--                角色-->
                <el-form-item prop="role" label="角色">
                    <el-select v-model="form.role" style="width: 300px" placeholder="请选择">
                        <el-option label="一级管理员" value="1"/>
                        <el-option label="二级管理员" value="2"/>
                        <el-option label="三级管理员" value="3"/>
                    </el-select>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="sub('ruleForm1')">添加</el-button>
            </div>
        </el-dialog>
    </div>


</template>

<script>
    import Title from "@/components/title/Title";
    import {Dialog,Form,FormItem,Option,Select,Input,Table, TableColumn, Button, MessageBox} from "element-ui";
    import Pagination from "@/components/pagination/Pagination";
    import {post} from "@/request/AxiosMAX";
    export default {
        name: "AddUser",
        components: {
            "el-table": Table,
            "el-table-column": TableColumn,
            "el-button": Button,
            Pagination,
            Title,
            "el-input":Input,
            "el-form":Form,
            "el-form-item":FormItem,
            "el-select":Select,
            "el-dialog":Dialog,
            "el-option":Option
        },
        data() {
            const checkEmail = (rule, value, callback) => {
                const $regEmal =/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
                post("/api/Studies_to_travel/user/emailIsExist",{email:value})
                    .then(res=>{
                        if (res.code===0){
                            if (value==='') {
                                return callback(new Error('邮箱不能为空'));
                            }else  if (!$regEmal.test(value)) {
                                setTimeout(() => {callback(new Error('输入的邮箱地址不合法')); }, 300);
                            }else if(res.data){
                                return callback(new Error('邮箱已被注册'));
                            }else {
                                callback();
                            }
                        }
                    });
            };
            let validatePass = (rule, value, callback) => {
                const $regPass = /^[a-z0-9]{6,16}$/;
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else if (!$regPass.test(value)) {
                    setTimeout(() => callback(new Error('输入的密码不合法')), 100);
                }else {
                    callback();
                }
            };
            let validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.form.pwd) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            let validatePhone = (rule, value, callback) =>{
                const  $reg = /^1[3-9]\d{9}$/;
                post("/api/Studies_to_travel/user/phoneIsExist",{phone:value})
                    .then(res=>{
                        if (res.code===0){
                            if (value === ''){
                                callback(new Error('手机号不能为空'))
                            } else if (res.data){
                                callback(new Error('手机号已被注册'))
                            }else if(!$reg.test(value)){
                                callback(new Error('手机号格式错误'))
                            }
                            else callback();
                        }
                    });

            };
            return {
                //验证1
                rules: {
                    pwd: [
                        { required: true,validator: validatePass, trigger: 'blur'}
                    ],
                    checkPass: [
                        { required: true, validator: validatePass2, trigger: 'blur'}
                    ],
                    email: [
                        { required: true, validator: checkEmail, trigger: 'blur'}
                    ],
                    phone: [
                        {
                            required: true,  validator: validatePhone, trigger: 'blur'
                        }
                    ],
                    role:[
                        { required: true, message: '请选择角色', trigger: 'change' }
                    ]
                },
                dialogFormVisible:false,
                tableData: [],
                count:0,
                item:{
                    startNumber:1,
                    pageSize:6,
                    groupId:this.$route.query.group.id
                },
                form:{
                    phone:'',
                    email:'',
                    pwd:'',
                    role:'',
                    state:0,
                    groupId:this.$route.query.group.id,
                    groupTypeId:this.$route.query.group.groupTypeId
                }
            }
        },
        methods: {
            //添加的方法
            sub(formName){
                this.$refs[formName].validate((valid) => {
                    if (valid){
                        post("/api/Studies_to_travel/user/addUser",this.form)
                            .then(res=>{
                                if (res.code===0){
                                    //添加到首位
                                    this.tableData.unshift(res.data);
                                    //清楚表单数据
                                    this.$refs[formName].resetFields();
                                    //关闭
                                    this.dialogFormVisible = false;
                                    this.$message({
                                        message: '添加成功~',
                                        type: 'success'
                                    });
                                }else {
                                    this.$message({
                                        message: '添加失败~',
                                        type: 'error'
                                    });
                                }
                            })
                            .catch(err=>{
                                console.info(err);
                                this.$message({
                                    message: '网络错误~',
                                    type: 'error'
                                });
                            });
                    }
                })
            },
            handleEdit(index, row) {
                console.log(index, row);
                this.dialogFormVisible = true;
            },
            //删除
            handleDelete(index, row) {
                MessageBox.confirm ('确定删除此角色吗？,是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //发送亲求
                    post("/api/Studies_to_travel/user/remove",{id:row.id})
                        .then(res=>{

                            if (res.code===0){
                                this.$message({
                                    type: 'success',
                                    message: '删除成功!'
                                });
                                //删除删除的数据
                                this.tableData.splice(index,1);
                            }else {
                                this.$message({
                                    type: 'error',
                                    message: '删除失败!'
                                });
                            }
                        }).catch(err=>{
                        console.info(err);
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //接收分页数据
            transfer(item){
                this.tableData = item.data;
                this.count = item.count;
            },
            //返回数据列表
            exit(){
                this.$router.push("/admin/view");
            }
        },
        created() {
            //获得机构下的用户
            post("/api/Studies_to_travel/user/queryGroupByPages",this.item)
                .then(res=>{
                    if (res.code===0){
                        //设置数据
                        this.tableData = res.data;
                        this.count = res.count;
                    }
                })
                .catch(err=>{
                    console.info(err)
                });
        }
    }
</script>

<style lang="less">
    #form{
        .form{
            display: flex;
        }
        .grname1{
            font-size: 25px;
        }
        .grname,.gradd,.type{
            font-size: 20px;
            margin-left: 10%;
            color: rgba(0,0,0,0.7);
        }
    }
</style>
